<template>
  <div>
    <div class="all" v-show="!dialogVisible">
      <div class="search_box">
        <div>
          <div class="search_title">标题</div>
          <div>
            <el-input v-model="input1" class="seek" placeholder="请输入标题" />
          </div>
        </div>
        <div class="search_right">
          <div class="search_title">创建时间</div>
          <div>
            <el-date-picker v-model="value1" type="daterange" range-separator="至" start-placeholder="开始时间"
              end-placeholder="结束时间" size="default" @change="debouncedSearch" />
          </div>
        </div>
      </div>
      <div class="line"></div>
      <div class="button_box">
        <el-button type="primary" class="butten" @click="adds()">新增</el-button>
        <el-button type="danger" class="butten" @click="deleteSelectedRows">批量删除</el-button>
      </div>
      <div class="table_box">
        <el-table :data="filteredData" ref="multipleTableRef"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="序号" width="120" align="center">
            <template #default="scope">{{ scope.row.id }}</template>
          </el-table-column>
          <el-table-column label="标题" show-overflow-tooltip align="center">
            <template #default="scope">{{ scope.row.title }}</template>
          </el-table-column>
          <el-table-column label="内容" width="300" show-overflow-tooltip align="center">
            <template #default="scope" align="center">{{ scope.row.content }}</template>
          </el-table-column>
          <el-table-column label="上下架" align="center">
            <template #default="scope">
              <el-switch v-model="scope.row.showBoolean" @change="changeSwitch(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column property="createtime" label="创建时间" align="center" />
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button type="primary" text @click="editRow(scope.row)">编辑</el-button>
              <el-button type="danger" text @click="deleteRow(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="demo-pagination-block">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
            @current-change="fetchData" @size-change="fetchData" layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[10, 20, 30, 40]" />
        </div>
      </div>
    </div>
    <!-- 添加遮罩层 -->
    <div v-show="dialogVisible" class="dialog-mask" @click="resetForm"></div>

    <div class="windows" v-show="dialogVisible">
      <div class="windows_box">
        <div class="windows_title">{{ titles }}</div>
        <div class="line"></div>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules">
          <div class="windows_content">
            <div class="content_left">
              <el-form-item label="标题" prop="title">
                <el-input v-model="ruleForm.title" placeholder="请输入标题" class="inputs"/>
              </el-form-item>
              <el-form-item label="内容" prop="content">
                <el-input v-model="ruleForm.content" placeholder="请输入内容" type="textarea" class="inputs"
                  rows="6" />
              </el-form-item>
            </div>
          </div>
          <div class="windows_content_box">
            <el-form-item>
              <el-button type="primary" @click="submitForm(ruleFormRef)">
                确定
              </el-button>
              <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import { reactive, onMounted, ref, watch, nextTick, onActivated, markRaw } from "vue";
import * as echarts from "echarts";
import { storeToRefs } from "pinia";
import { useThemeConfig } from "/@/stores/themeConfig";
import { useTagsViewRoutes } from "/@/stores/tagsViewRoutes";
import { noticeGet, noticeAdd, noticedel, noticeStatus } from "/@/api/public/notice";
import { url } from "/@/api/url";
import "/src/css/business.css";

const ruleFormRef = ref();//表单
const data = ref([]);//表格数据
const originalData = ref([]);//原始数据
const filteredData = ref([]);// 过滤后的数据
const value1 = ref(null);//搜索框
const input1 = ref("");   // 输入框的值
const currentPage = ref(1);//当前页
const pageSize = ref(10);// 每页显示的记录数
const total = ref(0);//总记录数
const dialogVisible = ref(false);//弹窗
const multipleTableRef = ref();//多选框
const selectedRows = ref<any[]>([]);//多选框选中的行
const titles = ref("");//标题
// 数据
const ruleForm = reactive({
  title: "",
  content: "",
  showBoolean: false,
  createtime: "",
  id: "",
  state: "1",
});
// 定义响应式数据
type SwiperItem = {
  id: number;
  showBoolean: boolean;
  img: string;
  updatetime: string;
};

// 自定义验证函数：检查是否仅包含空格
const validateNoOnlyWhitespace = (rule: any, value: string, callback: Function) => {
  // 去除两端空格后检查是否为空
  if (value.trim() === '') {
    callback(new Error(rule.message));
  } else {
    callback();
  }
};

// 表单验证
// 定义表单验证规则
const rules = {
  title: [
    { required: true, message: "请输入标题", trigger: "blur" },
    { validator: validateNoOnlyWhitespace, message: "不能只有空格", trigger: "blur" }
  ],
  content: [
    { required: true, message: "请输入内容", trigger: "blur" },
    { validator: validateNoOnlyWhitespace, message: "不能只有空格", trigger: "blur" }
  ],
};

// 获取数据
const fetchData = (params = { page: currentPage.value, pageSize: pageSize.value }) => {
  noticeGet(params)
    .then((res) => {
      console.log(res.data); // 查看 data 值

      originalData.value = res.data.map((item: any) => ({
        ...item,
        showBoolean: item.state === "1",
      }));
      filteredData.value = [...originalData.value];
      total.value = res.total || res.data.length;
    })
    .catch((error) => {
      ElMessage.error("获取数据失败，请稍后再试！");
    });
};

onMounted(() => {
  fetchData();
});
watch([input1, value1], () => {
  search();
});
//上下架
const changeSwitch = (item: any) => {
  const data = {
    id: item.id,
    state: item.showBoolean ? "1" : "0",
  };
  noticeStatus({
    id: item.id,
    state: item.showBoolean ? "1" : "2",
  })
    .then((res) => {
      ElMessage.success("操作成功！");
      fetchData();
    })
    .catch((error) => {
      ElMessage.error("操作失败，请稍后再试！");
    });
};
// 搜索过滤数据
const search = () => {
  let filtered = originalData.value;

  // 根据标题过滤
  if (input1.value) {
    filtered = filtered.filter((item: any) =>
      item.title?.toLowerCase().includes(input1.value.toLowerCase())
    );
  }

  // 根据日期范围过滤
  if (value1.value && value1.value[0] && value1.value[1]) {
    const startTime = new Date(value1.value[0]).getTime();
    const endTime = new Date(value1.value[1]).getTime();

    filtered = filtered.filter((item: any) => {
      const itemTime = new Date(item.createtime).getTime();
      return itemTime >= startTime && itemTime <= endTime;
    });
  }

  filteredData.value = filtered;
  total.value = filtered.length;
  currentPage.value = 1; // 重置当前页码
};

// 使用防抖机制
let debounceTimer: NodeJS.Timeout | null = null;
// 定义防抖函数
const debouncedSearch = () => {
  if (debounceTimer) clearTimeout(debounceTimer);
  debounceTimer = setTimeout(search, 500);
};
// 新增逻辑
const adds = () => {
  titles.value = "新增";
  dialogVisible.value = true;
};

// 编辑逻辑
const editRow = (row: any) => {
  titles.value = "编辑";
  dialogVisible.value = true;
  // 填充表单数据
  Object.assign(ruleForm, row);
};
// 重置表单
const resetForm = (formEl?: any) => {
  if (formEl) {
    formEl.resetFields();
  }
  ruleForm.id = "";
  ruleForm.title = "";
  ruleForm.content = "";
  ruleForm.showBoolean = false;
  ruleForm.createtime = "";
  dialogVisible.value = false; // 关闭弹窗
};
// 处理表格选择变化
const handleSelectionChange = (val: any[]) => {
  selectedRows.value = val;
};

// 提交表单
const submitForm = async (formEl: any) => {
  if (!formEl) return;

  // 调用表单验证方法
  formEl.validate(async (valid: boolean) => {
    if (valid) {
      // 验证通过，提交数据
      try {
        const res = await noticeAdd(ruleForm);
        console.log(res);
        if (res.code === 1) {
          ElMessage.success("提交成功!");
          dialogVisible.value = false;
          fetchData(); // 刷新数据
          resetForm(formEl); // 重置表单
        } else {
          ElMessage.error(res.message || "提交失败，请稍后再试！");
        }
      } catch (error) {
        ElMessage.error("提交失败，请稍后再试！");
      }
    } else {
      // 验证不通过，提示错误
      ElMessage.warning("请填写完整信息！");
      return false;
    }
  });
};
// 单行删除
const deleteRow = async (row: SwiperItem) => {
  try {
    await ElMessageBox.confirm("确定要删除该条记录吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    await noticedel({ id: row.id }); // 调用 API 删除数据
    ElMessage.success("删除成功！");

    // 更新本地数据
    originalData.value = originalData.value.filter((item: SwiperItem) => item.id !== row.id);
    filteredData.value = filteredData.value.filter((item: SwiperItem) => item.id !== row.id);
    total.value--;
  } catch (error) {
    ElMessage.error("删除失败，请稍后再试！");
  }
};

// 批量删除
const deleteSelectedRows = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要删除的记录");
    return;
  }

  try {
    await ElMessageBox.confirm("确定要删除选中的记录吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const idsToDelete = selectedRows.value.map((row: { id: any; }) => row.id);
    //转字符串
    const ids = idsToDelete.join(",");

    await noticedel({ id: idsToDelete }); // 调用 API 批量删除数据
    console.log(idsToDelete);

    ElMessage.success("删除成功！");

    // 更新本地数据
    originalData.value = originalData.value.filter(
      (item: SwiperItem) => !idsToDelete.includes(item.id)
    );
    filteredData.value = filteredData.value.filter(
      (item: SwiperItem) => !idsToDelete.includes(item.id)
    );
    total.value -= idsToDelete.length;

    // 清空选中状态
    selectedRows.value = [];
    multipleTableRef.value.clearSelection();
  } catch (error) {
    ElMessage.error("删除失败，请稍后再试！");
  }
};
</script>

<style scoped></style>